package com.android.djlmapp.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.djlmapp.R;
import com.android.djlmapp.activity.order.OrderDetailActivity;
import com.android.djlmapp.adapter.order.AllOrderListAdapter;
import com.android.djlmapp.adapter.order.BroadBandOrderListAdapter;
import com.android.djlmapp.adapter.order.FlowChargeListAdapter;
import com.android.djlmapp.adapter.order.GameChargeOrderListAdapter;
import com.android.djlmapp.adapter.order.KkOrderListAdapter;
import com.android.djlmapp.adapter.order.OrderListAdapter;
import com.android.djlmapp.adapter.order.QbChargeOrderListAdapter;
import com.android.djlmapp.adapter.order.TelChargeOrderListAdapter;
import com.android.djlmapp.adapter.order.TerminalOrderListAdapter;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.base.BaseFragment;
import com.android.djlmapp.http.ComPareUtils;
import com.android.djlmapp.http.GlobalUrls;
import com.android.djlmapp.model.order.OrderListInfo;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.djlmapp.tools.global.UserInfoUtils;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.refresh_view.pullrecyclerview.PullRecyclerView;
import org.refresh_view.pullrecyclerview.layoutmanager.XLinearLayoutManager;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.android.djlmapp.activity.home.web.base.BaseWebActivity.PAGE_URL_KEY;
import static com.android.djlmapp.activity.order.OrderDetailActivity.ORDER_DETAIL_ORDER_SN_KEY;

/**
 * @Author wangziheng
 * @ProjectName djlm
 * @ClassName ChildOrderFragment
 * @package com.android.djlmapp.fragment.order
 * @data 2018/12/5 18:48
 * @Describe 子订单列表
 * @Change
 */
public class ChildOrderFragment extends BaseFragment {

    private static final String TAG = "ChildOrderFragment";
    public static final int ALL_ORDER_TYPE = 8;
    /**
     * 开卡订单
     */
    public static final int KAIKA_ORDER_TYPE = 0;
    /**
     * 话费充值订单
     */
    public static final int TEL_CHARGE_ORDER_TYPE = 1;
    /**
     * 流量充值订单
     */
    public static final int FLOW_CHARGE_ORDER_TYPE = 2;
    /**
     * 宽带订单
     */
    public static final int BROADBAND_ORDER_TYPE = 3;
    /**
     * 终端订单
     */
    public static final int TERMINAL_ORDER_TYPE = 4;
    /**
     * Q币充值订单
     */
    public static final int Q_MONEY_CHARGE_ORDER_TYPE = 5;
    /**
     * 游戏充值订单
     */
    public static final int GAME_CHARGE_ORDER_TYPE = 6;
    /**
     * 订单类型数组
     */
    public static final int[] ORDER_TYPE = {ALL_ORDER_TYPE, KAIKA_ORDER_TYPE, TEL_CHARGE_ORDER_TYPE, FLOW_CHARGE_ORDER_TYPE,
            BROADBAND_ORDER_TYPE, TERMINAL_ORDER_TYPE, Q_MONEY_CHARGE_ORDER_TYPE, GAME_CHARGE_ORDER_TYPE};
    /**
     * 订单类型键值
     */
    public static final String ORDER_TYPE_KEY = "ORDER_TYPE_KEY";
    public static final String ORDER_TYPE_KEY_CODE = "ORDER_TYPE_KEY_CODE";
    @BindView(R.id.null_data_layout_img)
    ImageView nullDataLayoutImg;
    Unbinder unbinder;
    /**
     * 订单类型Value值
     */
    private String mOrderType;
    /**
     * 订单类型Code值
     */
    private int mOrderTypeCode;
    /**
     * 搜索内容
     */
    private String mSearchContent;

    /**
     * 当前页数
     */
    private int mPageSize = 1;
    /**
     * 当前界面是否有数据
     */
    private boolean isHadData = false;

    /**
     * 是否需要清空列表数据
     */
    private boolean isClearData = false;
    /**
     * 当前操作是否是搜索订单操作
     */
    private boolean isSearchOrder = false;
    @BindView(R.id.pull_recycler_view)
    PullRecyclerView mPullRecyclerView;
    private OrderListAdapter mOrderAdapter;

    @BindView(R.id.null_data_layout_txt)
    TextView mNullDataWarningTv;
    @BindView(R.id.null_data_layout)
    RelativeLayout mNullDataLayout;
    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectNetErrorLayout;
    /**
     * 第一次加载
     */
    private boolean isFirst = true;
    public static ChildOrderFragment getInstance(String orderType, int orderTypeCode) {
        if (TextUtils.isEmpty(orderType)) {
            throw new NullPointerException("订单类型不能为空:ChildOrderFragment#getInstance : orderType == null");
        }
        ChildOrderFragment childOrderFragment = new ChildOrderFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ORDER_TYPE_KEY, orderType);
        bundle.putInt(ORDER_TYPE_KEY_CODE, orderTypeCode);
        childOrderFragment.setArguments(bundle);
        return childOrderFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mOrderType = bundle.getString(ORDER_TYPE_KEY);
            mOrderTypeCode = bundle.getInt(ORDER_TYPE_KEY_CODE);
        }
    }
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_child_order_layout, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    /**
     * 无数据时的提示信息
     */
    private String mWarnningMsg = "暂无该订单信息";

    /**
     * 设置无数据时的提示信息
     */
    private void setNullDataWarningMsg() {

        // 设置无数据时的提示信息
        mNullDataWarningTv.setText(mWarnningMsg);
    }

    DingDanLieBiaoFragment mParentFragment;

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden && !isHadData && !isFirst){
            normalLayout();
            mPullRecyclerView.autoRefresh();
        }
    }

    private DingDanLieBiaoFragment getParentFt(){
        if(mParentFragment == null){
            mParentFragment = (DingDanLieBiaoFragment) getParentFragment();
        }
        return mParentFragment;
    }
    @Override
    public void initView() {
        nullDataLayoutImg.setImageResource(R.mipmap.order_zwdd);
        setNullDataWarningMsg();
        mOrderAdapter = getOrderAdapter();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mPullRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    hindSoftInput();
                }
            });
        }
        mPullRecyclerView.setLayoutManager(new XLinearLayoutManager(getContext()));
        mPullRecyclerView.setAdapter(mOrderAdapter);
        mPullRecyclerView.enableLoadMore(false);
        mPullRecyclerView.setColorSchemeResources(R.color.homeBule);
        mPullRecyclerView.setOnRecyclerRefreshListener(new PullRecyclerView.OnRecyclerRefreshListener() {
            @Override
            public void onPullRefresh() {
                setNullDataWarningMsg();
                isClearData = true;
                mPullRecyclerView.enableLoadMore(false);
                mPageSize = 1;
                mSearchContent = null;
                getParentFt().clearSearchEd();
                // 刷新列表 分为搜索状态下的刷新和普通状态下的刷新  加载同理
                requestData();
            }

            @Override
            public void onLoadMore() {
                requestData();
            }
        });

        // 点击事件
        mOrderAdapter.setOnRecyclerItemClickListener((view, position) -> {
            hindSoftInput();
            OrderListInfo.DataBean dataBean = mOrderAdapter.getItem(position);
            String orderDetailPath = dataBean.getOrder_info();
            if (!TextUtils.isEmpty(orderDetailPath)) {
                String token = UserInfoUtils.getUserInfoUtilsInstance().getToken();
                String version = UserInfoUtils.getUserInfoUtilsInstance().getVersion();
                String orderSn = dataBean.getOrder_sn();
                String signKK = new ComPareUtils.ComPareBuilder()
                        .put("token", token)
                        .put("version", version)
                        .put("order_sn", orderSn)
                        .create()
                        .getSignString();
                orderDetailPath = GlobalUrls.MAIN_URL + orderDetailPath + "?sign=" + signKK + "&token=" + token + "&version=" + version + "&order_sn=" + orderSn;
                Intent intent = new Intent(_mActivity, OrderDetailActivity.class);
                intent.putExtra(ORDER_DETAIL_ORDER_SN_KEY, orderSn);
                intent.putExtra(PAGE_URL_KEY, orderDetailPath);
                startActivity(intent);
            }
        });

        if(mOrderTypeCode == ALL_ORDER_TYPE){
            new Handler().postDelayed(() -> mPullRecyclerView.autoRefresh(), 500);
        }else {
            mPullRecyclerView.autoRefresh();
        }
    }

    private void requestData() {
        if (isSearchOrder) {
            searchOrderData();
        } else {
            requestOrderData();
        }
    }

    public void searchOrder(String searchContent) {
        mSearchContent = searchContent;
        // 如果搜索内容为空 则请求全部订单  不为空则进行搜索
        if (TextUtils.isEmpty(mSearchContent)) {
            isSearchOrder = false;
        } else {
            isSearchOrder = true;
        }
        isClearData = true;
        mPullRecyclerView.enableLoadMore(false);
        mPageSize = 1;
        requestData();
    }

    @Override
    public void initData() {

    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        isFirst = false;
        initView();
    }

    /**
     * 请求订单列表
     */
    private void requestOrderData() {
        MyApplication.getInstance().getHttpTools().requestOrder(mOrderTypeCode == ALL_ORDER_TYPE ? null : String.valueOf(mOrderTypeCode), String.valueOf(mPageSize), mStringCallBack);
    }

    /**
     * 搜索订单
     */
    private void searchOrderData() {
        MyApplication.getInstance().getHttpTools().searchOrderData(mOrderTypeCode == ALL_ORDER_TYPE ? null : String.valueOf(mOrderTypeCode), mSearchContent, mStringCallBack);
    }

    private StringCallback mStringCallBack = new StringCallback() {
        @Override
        public void onSuccess(Response<String> response) {
            try {
                String str = response.body();
                Gson gson = new Gson();
                OrderListInfo orderListInfo = gson.fromJson(str, OrderListInfo.class);
                if (orderListInfo != null) {
                    List<OrderListInfo.DataBean> orderListBean = orderListInfo.getData();
                    // 如果返回值为200并且有数据 则正常显示布局
                    if (orderListInfo.getCode() == 200 && orderListBean != null && orderListBean.size() > 0) {
                        normalLayout();
                        // 判断是否需要清空数据  (如果是刷新操作或是搜索操作，则需要清空数据)
                        // 如果需要清空 则需要先清空数据 然后再添加新数据
                        if (isClearData) {
                            isClearData = false;
                            isHadData = false;
                            mOrderAdapter.clear();
                        }
                        if (orderListBean.size() >= 15 && !isSearchOrder) {
                            mPageSize++;
                            mPullRecyclerView.enableLoadMore(true);
                        } else {
                            mPullRecyclerView.enableLoadMore(false);
                        }
                        isHadData = true;
                        /**
                         * 每次请求完毕  都将请求类型修改为非搜索状态
                         */
                        if (isSearchOrder) {
                            isSearchOrder = !isSearchOrder;
                        }
                        mOrderAdapter.addAll(orderListBean);
                    } else {
                        if (isSearchOrder) {
//                            ToastUtils.showShortToast(getContext(), "没有搜索到该订单数据");
//                            // 如果没有搜索到数据 则请求全部数据
//                            requestOrderData();
                            isHadData = false;
                            isSearchOrder = !isSearchOrder;
                            mOrderAdapter.clear();
                            setNullDataWarningMsg();
                            noDataLayout();
                        } else {
                            if(isHadData){
                                showErrorLayout(false, orderListInfo.getMsg());
                            }else {
                                setNullDataWarningMsg();
                                noDataLayout();
                            }
                        }
                    }
                } else {
                    showErrorLayout(false, "服务端异常");
                }
            } catch (Exception jsonExce) {
            }
        }

        @Override
        public void onError(Response<String> response) {
            if (mPullRecyclerView != null) {
                isClearData = false;
                showErrorLayout(true, getString(R.string.connect_sever_error_msg));
            }
        }

        @Override
        public void onFinish() {
            if (mPullRecyclerView != null) {
                mPullRecyclerView.stopLoadMore();
                mPullRecyclerView.stopRefresh();
            }
        }
    };

    @OnClick({R.id.requery_data_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.requery_data_tv:
                mPullRecyclerView.autoRefresh();
                break;
            default:
                break;

        }
    }

    /**
     * 显示布局
     *
     * @param isNetError  是否是网络错误
     * @param warnningMsg 提示信息
     */
    private void showErrorLayout(boolean isNetError, String warnningMsg) {
        mPullRecyclerView.enableLoadMore(false);
        if (isHadData) {
            normalLayout();
            ToastUtils.showShortToastSafe(getContext(), warnningMsg);
        } else {
            if (isNetError) {
                connectNetErrorLayout();
            } else {
                noDataLayout();
            }
        }
    }

    /**
     * 无数据状态
     */
    private void noDataLayout() {
        if (mNullDataLayout.getVisibility() == View.GONE) {
            mConnectNetErrorLayout.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 网络错误状态
     */
    private void connectNetErrorLayout() {
        if (mConnectNetErrorLayout.getVisibility() == View.GONE) {
            mNullDataLayout.setVisibility(View.GONE);
            mConnectNetErrorLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 正常布局状态
     */
    private void normalLayout() {
        if (mConnectNetErrorLayout.getVisibility() == View.VISIBLE || mNullDataLayout.getVisibility() == View.VISIBLE) {
            mConnectNetErrorLayout.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 获取对应的适配器类型
     *
     * @return
     */
    private OrderListAdapter getOrderAdapter() {
        OrderListAdapter orderListAdapter = null;
        switch (mOrderTypeCode) {
            case KAIKA_ORDER_TYPE:
                orderListAdapter = new KkOrderListAdapter(_mActivity);
                break;
            case TEL_CHARGE_ORDER_TYPE:
                orderListAdapter = new TelChargeOrderListAdapter(_mActivity);
                break;
            case FLOW_CHARGE_ORDER_TYPE:
                orderListAdapter = new FlowChargeListAdapter(_mActivity);
                break;
            case BROADBAND_ORDER_TYPE:
                orderListAdapter = new BroadBandOrderListAdapter(_mActivity);
                break;
            case TERMINAL_ORDER_TYPE:
                orderListAdapter = new TerminalOrderListAdapter(_mActivity);
                break;
            case Q_MONEY_CHARGE_ORDER_TYPE:
                orderListAdapter = new QbChargeOrderListAdapter(_mActivity);
                break;
            case GAME_CHARGE_ORDER_TYPE:
                orderListAdapter = new GameChargeOrderListAdapter(_mActivity);
                break;
            case ALL_ORDER_TYPE:
                orderListAdapter = new AllOrderListAdapter(_mActivity);
                break;
            default:
                break;
        }
        return orderListAdapter;
    }

    public void hindSoftInput() {
        InputMethodManager imm =
                (InputMethodManager) _mActivity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }
        View view = _mActivity.getCurrentFocus();
        if (view == null) {
            view = new View(getContext());
        }
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
